package hello

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"os"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/go-flutter-desktop/go-flutter"
	"github.com/go-flutter-desktop/go-flutter/plugin"
)

// go-flutter插件需要声明包名和函数名
// dart代码中调用时需要指定相应的包名和函数名
const (
	accessKeySecret  = "G6x3EPIVE2idZXKe5hKzl2WAuBSag3"
	accessKeyID      = "LTAI5tSaaMEaixDCDXvvpr6T"
	endPoint         = "oss-cn-shenzhen.aliyuncs.com"
	oss_bucketName   = "webplus-cn-shenzhen-s-60d3dd41f968dd14ceace7d8"
	oss_channelName  = "bettersun.go-flutter.plugin.oss"
	oss_delectObject = "delectObject"
	oss_listObject   = "listObject"
	oss_putObject    = "putObject"
)

func handleError(err error) {
	fmt.Println("Error:", err)
	os.Exit(-1)
}

// 声明插件结构体
type OssPlugin struct{}

// 指定为go-flutter插件
var _ flutter.Plugin = &OssPlugin{}

// 初始化插件
func (OssPlugin) InitPlugin(messenger plugin.BinaryMessenger) error {
	channel := plugin.NewMethodChannel(messenger, oss_channelName, plugin.StandardMethodCodec{})
	channel.HandleFunc(oss_delectObject, delectObjectPlugin)
	channel.HandleFunc(oss_listObject, getObjectList)
	channel.HandleFunc(oss_putObject, putObjectPlugin)
	return nil
}

func initOss() (*oss.Bucket, error) {
	client, err := oss.New(endPoint, accessKeyID, accessKeySecret)
	if err != nil {
		handleError(err)
		return nil, errors.New("oss初始化失败")
	}
	// 获取存储空间。
	bucketName := oss_bucketName
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		handleError(err)
		return nil, errors.New("oss初始化失败")
	}
	fmt.Println("oss 初始化成功")
	return bucket, nil
}

//获取数据列表
func getObjectList(arguments interface{}) (reply interface{}, err error) {
	var param = arguments.(string)
	fmt.Println("param: ", param)
	var retPathStr []string
	bucket, err := initOss()
	if err != nil {
		handleError(err)
		return nil, err
	}
	// 列举所有文件。
	marker := ""
	marker = param

	for {
		prefix := oss.Prefix(marker)
		lsRes, err := bucket.ListObjects(oss.Marker(""), prefix)
		if err != nil {
			handleError(err)
		}

		// 打印列举结果。默认情况下，一次返回100条记录。
		for _, object := range lsRes.Objects {
			retPathStr = append(retPathStr, object.Key)
			// 			fmt.Println("Bucket: ", object.Key)
		}

		if lsRes.IsTruncated {
			marker = lsRes.NextMarker
		} else {
			break
		}
	}
	if len(retPathStr) == 0 {
		return nil, errors.New("数据为空")
	}
	data, _ := json.Marshal(retPathStr)
	if err != nil {
		handleError(err)
		return nil, err
	}
	return string(data), nil

}

// 具体的逻辑处理函数，有参数传递
func delectObjectPlugin(arguments interface{}) (reply interface{}, err error) {
	var param = arguments.(string)
	bucket, err := initOss()
	if err != nil {
		handleError(err)
		return false, err
	}
	// Delete object, deletes an object
	err = bucket.DeleteObject(param)
	if err != nil {
		handleError(err)
		return false, errors.New("删除失败：" + err.Error())
	}

	// 	// Put object, uploads an object
	//     	var objectName = "myobject"
	//     	err = bucket.PutObject(objectName, strings.NewReader("MyObjectValue"))
	//     	if err != nil {
	//     		HandleError(err)
	//     	}

	return true, nil
}

// 上传数据
func putObjectPlugin(arguments interface{}) (reply interface{}, err error) {
	argumentsMap := arguments.(map[interface{}]interface{})
	var path = ""

	for p := range argumentsMap {
		path = p.(string)
	}
	fmt.Println(path)
	var data = bytes.NewReader(argumentsMap[path].([]byte))
	bucket, err := initOss()
	if err != nil {
		handleError(err)
		return false, err
	}

	// 上传Byte数组。
	err = bucket.PutObject(path, data)
	if err != nil {
		handleError(err)
		return false, err
	}

	return true, nil
}
